#!/bin/bash

# Docker部署脚本
set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 默认值
ENVIRONMENT="dev"
COMPOSE_FILE="docker-compose.yml"
IMAGE_NAME="nest-base"
TAG="latest"

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -e|--env)
            ENVIRONMENT="$2"
            shift 2
            ;;
        -f|--file)
            COMPOSE_FILE="$2"
            shift 2
            ;;
        -t|--tag)
            TAG="$2"
            shift 2
            ;;
        -h|--help)
            echo "用法: $0 [选项]"
            echo "选项:"
            echo "  -e, --env ENV      环境 (dev|prod, 默认: dev)"
            echo "  -f, --file FILE    compose文件 (默认: docker-compose.yml)"
            echo "  -t, --tag TAG      镜像标签 (默认: latest)"
            echo "  -h, --help         显示帮助信息"
            exit 0
            ;;
        *)
            print_error "未知选项: $1"
            exit 1
            ;;
    esac
done

# 根据环境设置compose文件
if [ "$ENVIRONMENT" = "prod" ]; then
    COMPOSE_FILE="docker-compose.prod.yml"
    print_message "使用生产环境配置: $COMPOSE_FILE"
else
    print_message "使用开发环境配置: $COMPOSE_FILE"
fi

print_message "开始部署Docker服务..."
print_message "环境: $ENVIRONMENT"
print_message "Compose文件: $COMPOSE_FILE"
print_message "镜像标签: $TAG"

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    print_error "Docker未运行，请启动Docker服务"
    exit 1
fi

# 检查compose文件是否存在
if [ ! -f "$COMPOSE_FILE" ]; then
    print_error "Compose文件不存在: $COMPOSE_FILE"
    exit 1
fi

# 停止现有服务
print_message "停止现有服务..."
docker-compose -f "$COMPOSE_FILE" down

# 清理未使用的镜像和容器
print_message "清理未使用的资源..."
docker system prune -f

# 启动服务
print_message "启动服务..."
docker-compose -f "$COMPOSE_FILE" up -d

# 等待服务启动
print_message "等待服务启动..."
sleep 10

# 检查服务状态
print_message "检查服务状态..."
docker-compose -f "$COMPOSE_FILE" ps

# 检查健康状态
print_message "检查健康状态..."
for i in {1..30}; do
    if docker-compose -f "$COMPOSE_FILE" ps | grep -q "Up"; then
        print_message "服务启动成功!"
        break
    fi
    print_warning "等待服务启动... ($i/30)"
    sleep 2
done

# 显示日志
print_message "显示服务日志..."
docker-compose -f "$COMPOSE_FILE" logs --tail=20

print_message "部署完成!"
print_message "访问地址: http://localhost:7001"
print_message "API文档: http://localhost:7001/api-docs" 